package com.example.dubbo.provider.service;

import com.example.dubbo.api.model.User;
import com.example.dubbo.api.service.UserService;
import org.apache.dubbo.config.annotation.DubboService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户服务实现类
 * @DubboService 注解将此类暴露为 Dubbo 服务
 */
@DubboService(version = "1.0.0", timeout = 5000)
public class UserServiceImpl implements UserService {
    
    // 模拟数据库存储
    private final Map<Long, User> userDatabase = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public UserServiceImpl() {
        // 初始化一些测试数据
        userDatabase.put(1L, new User(1L, "张三", "zhangsan@example.com", 25));
        userDatabase.put(2L, new User(2L, "李四", "lisi@example.com", 30));
        userDatabase.put(3L, new User(3L, "王五", "wangwu@example.com", 28));
        idGenerator.set(4L);
    }
    
    @Override
    public User getUserById(Long id) {
        System.out.println("Provider 收到请求: getUserById(" + id + ")");
        User user = userDatabase.get(id);
        if (user == null) {
            System.out.println("用户不存在: " + id);
            return null;
        }
        System.out.println("返回用户信息: " + user);
        return user;
    }
    
    @Override
    public List<User> getAllUsers() {
        System.out.println("Provider 收到请求: getAllUsers()");
        List<User> users = new ArrayList<>(userDatabase.values());
        System.out.println("返回用户数量: " + users.size());
        return users;
    }
    
    @Override
    public User createUser(User user) {
        System.out.println("Provider 收到请求: createUser(" + user + ")");
        Long id = idGenerator.getAndIncrement();
        user.setId(id);
        userDatabase.put(id, user);
        System.out.println("创建用户成功: " + user);
        return user;
    }
    
    @Override
    public Boolean deleteUser(Long id) {
        System.out.println("Provider 收到请求: deleteUser(" + id + ")");
        User removed = userDatabase.remove(id);
        boolean success = removed != null;
        System.out.println("删除用户" + (success ? "成功" : "失败") + ": " + id);
        return success;
    }
}

